﻿// 2023/3/8: 首个版本
// 2023/9/12: 修正英文日期显示
// 2023/9/25: 改为直接输入Icon对象
// 2024/3/27: 修正按钮宽度

using System;
using System.Collections.Generic;
using ASEva;
using ASEva.Samples;
using ASEva.UIEto;
using Eto.Drawing;
using Eto.Forms;

namespace CommonSource
{
    class SessionInfoEditor : DialogPanel
    {
        public SessionInfoEditor(DateTime session, Icon icon = null)
        {
            Icon = icon;
            Title = chinese ? "编辑数据片段信息" : "Edit session";
            SetFixMode(390, 450, true);

            this.session = session;

            var mainLayout = this.SetContentAsColumnLayout();
            var timeLayout = mainLayout.AddTableLayout();
            checkHostSync = mainLayout.AddCheckBox(chinese ? "主机与授时服务器已同步" : "Host synchronized with time server", false, Agency.GetSessionHostSync(session));
            var commentLayout = mainLayout.AddColumnLayout(false, 2);
            commentLayout.SetLogicalHeight(105);
            var propertyLayout = mainLayout.AddColumnLayout(true, 2);
            var buttonsLayout = mainLayout.AddRowLayout();

            var row = timeLayout.AddRow(true);
            row.AddLabel(chinese ? "开始时间:" : "Start time:");
            row.AddLabel(getStartTimeLocalText(), true);
            row = timeLayout.AddRow(true);
            row.AddLabel(chinese ? "数据时长:" : "Duration:");
            row.AddLabel(getTimeLengthText(), true);

            commentLayout.AddLabel(chinese ? "描述:" : "Comments:");
            textComment = commentLayout.AddControl(new TextArea(), true) as TextArea;
            var commentText = getCommentText();
            if (commentText != null) textComment.Text = commentText;

            var propTitleLayout = propertyLayout.AddRowLayout();
            propTitleLayout.AddLabel(chinese ? "属性:" : "Property:");
            propTitleLayout.AddSpace();
            var linkAdd = propTitleLayout.AddLinkButton(chinese ? "添加" : "Add");
            var linkRemove = propTitleLayout.AddLinkButton(chinese ? "移除" : "Remove");
            textTable = propertyLayout.AddControl(new TextTableView(), true) as TextTableView;
            textTable.AddColumn(chinese ? "键" : "Key", 100);
            textTable.AddColumn(chinese ? "值" : "Value", 230);

            var properties = Agency.GetSessionProperties(session);
            if (properties != null)
            {
                var list = new List<String[]>();
                foreach (var item in properties) list.Add(new String[] { item.Key, item.Value });
                textTable.AddRows(list);
            }

            var buttonOpen = buttonsLayout.AddButton(chinese ? "在文件浏览器打开" : "Open in file explorer");
            var buttonDelete = buttonsLayout.AddButton(chinese ? "删除" : "Delete", false, 80);
            buttonsLayout.AddSpace();
            var buttonOK = buttonsLayout.AddButton(chinese ? "确定" : "OK", false, 80);

            buttonDelete.Click += buttonDelete_Clicked;
            buttonOK.Click += buttonOK_Clicked;
            buttonOpen.Click += buttonOpen_Clicked;
            linkAdd.Click += linkAdd_Clicked;
            linkRemove.Click += linkRemove_Clicked;
        }

        private void buttonDelete_Clicked(object sender, EventArgs e)
        {
            if (Agency.RemoveSession(session, false)) Close();
        }

        private void buttonOpen_Clicked(object sender, EventArgs e)
        {
            var path = Agency.GetSessionPath(session);
            if (!Agency.StartProcess(path)) Agency.PopupError(chinese ? "无法打开session文件夹。" : "Failed to open the session's directory.");
        }

        private void buttonOK_Clicked(object sender, EventArgs e)
        {
            Agency.SetSessionHostSync(session, checkHostSync.Checked.Value);
            Agency.SetSessionComment(session, textComment.Text);

            var properties = new Dictionary<String, String>();
            for (int i = 0; i < textTable.GetRowCount(); i++)
            {
                var key = textTable.GetValue(i, 0);
                var value = textTable.GetValue(i, 1);

                if (String.IsNullOrEmpty(key) || value == null) continue;

                if (properties.ContainsKey(key))
                {
                    Agency.PopupError((chinese ? "键重复：" : "The key repeated: ") + key);
                    return;
                }
                else properties[key] = value;
            }
            Agency.SetSessionProperties(session, properties);

            Close();
        }

        private void linkAdd_Clicked(object sender, EventArgs e)
        {
            textTable.AddRow(new String[] { chinese ? "新属性" : "New property", "" });
        }

        private void linkRemove_Clicked(object sender, EventArgs e)
        {
            if (textTable.SelectedRow >= 0) textTable.RemoveRow(textTable.SelectedRow);
        }

        private String getStartTimeLocalText()
        {
            var startTimeLocal = Agency.GetStartTimeLocal(session);
            if (startTimeLocal == null)
            {
                return chinese ? "(未知)" : "(Unknown)";
            }
            else
            {
                return startTimeLocal.Value.ToString(chinese ? "yyyy/MM/dd HH:mm:ss +fff" : "MM/dd/yyyy HH:mm:ss +fff") + "ms";
            }
        }

        private String getTimeLengthText()
        {
            var interval = Agency.GetSessionLength(session);
            if (interval == null)
            {
                return chinese ? "(未知)" : "(Unknown)";
            }
            else
            {
                if (interval.Value < 1)
                {
                    return chinese ? "0秒" : "0 sec";
                }
                else
                {
                    var span = TimeSpan.FromSeconds(interval.Value);
                    var days = (int)span.TotalDays;
                    var hours = span.Hours;
                    var minutes = span.Minutes;
                    var seconds = span.Seconds;
                    var ms = span.Milliseconds;
                    var text = "";
                    text += (days > 0 ? (days + (chinese ? "天 " : " day ")) : "");
                    text += (hours > 0 ? (hours + (chinese ? "时 " : " hour ")) : "");
                    text += (minutes > 0 ? (minutes + (chinese ? "分 " : " min ")) : "");
                    text += (seconds > 0 ? (seconds + (chinese ? "秒 " : " sec ")) : "");
                    text += (ms > 0 ? (ms + (chinese ? "毫秒 " : " ms ")) : "");
                    return text;
                }
            }
        }

        private String getCommentText()
        {
            var comment = Agency.GetSessionComment(session);
            return comment == null ? "" : comment;
        }

        private DateTime session;
        private TextTableView textTable;
        private TextArea textComment;
        private CheckBox checkHostSync;
        private bool chinese = Agency.GetAppLanguage() == "ch";
    }
}
